package com.zrar.ak.gkpt.util;

import java.io.*;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * @ClassName: FileUtil
 * @Description: 文件工具类
 * @author: liyang
 * @date: 2020年2月25日
 */
public class FileUtil {

    public FileUtil() {
    }

    public static File uploadFile(InputStream in, String dir, String filename) throws IOException {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            if (null != dir) {
                dir = formatPath(dir);
            }

            if (stringIsNull(filename)) {
                throw new IllegalArgumentException("finename is empty");
            } else {
                filename = formatFileName(filename);
                File dirFile = new File(dir);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }

                File file = new File(dir, filename);
                file.createNewFile();
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                byte[] buffer = new byte[1024];

                int len;
                while((len = in.read(buffer)) > 0) {
                    bos.write(buffer, 0, len);
                }

                File var9 = file;
                return var9;
            }
        } finally {
            try {
                bos.close();
                fos.close();
                in.close();
            } catch (IOException var16) {
                var16.printStackTrace();
            }

        }
    }

    public static void writeFile(String fileName, String content) {
        writeFile(fileName, content, "utf-8");
    }

    public static void writeFile(String fileName, String content, String charset) {
        try {
            createFolder(fileName, true);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), charset));
            out.write(content);
            out.close();
        } catch (IOException var4) {
            var4.printStackTrace();
        }

    }

    public static void writeFile(String fileName, InputStream is) throws IOException {
        FileOutputStream fos = new FileOutputStream(fileName);
        byte[] bs = new byte[10240];
        boolean var4 = false;

        int n;
        while((n = is.read(bs)) != -1) {
            fos.write(bs, 0, n);
        }

        fos.flush();
        fos.close();
        is.close();
    }

    public static String readFile(String fileName) {
        try {
            File file = new File(fileName);
            String charset = getCharset(file);
            StringBuffer sb = new StringBuffer();
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), charset));

            String str;
            while((str = in.readLine()) != null) {
                sb.append(str + "\r\n");
            }

            in.close();
            return sb.toString();
        } catch (IOException var6) {
            var6.printStackTrace();
            return "";
        }
    }

    public static String readFile(InputStream in, String charset) {
        try {
            StringBuffer sb = new StringBuffer();
            byte[] b = new byte[in.available()];

            while(in.read(b) != -1) {
                sb.append(new String(b, charset));
            }

            in.close();
            return sb.toString();
        } catch (IOException var4) {
            var4.printStackTrace();
            return "";
        }
    }

    public static String getCharset(File file) {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];

        try {
            boolean checked = false;
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1) {
                return charset;
            }

            if (first3Bytes[0] == -1 && first3Bytes[1] == -2) {
                charset = "UTF-16LE";
                checked = true;
            } else if (first3Bytes[0] == -2 && first3Bytes[1] == -1) {
                charset = "UTF-16BE";
                checked = true;
            } else if (first3Bytes[0] == -17 && first3Bytes[1] == -69 && first3Bytes[2] == -65) {
                charset = "UTF-8";
                checked = true;
            }

            bis.reset();
            if (!checked) {
                int var6 = 0;

                label74:
                do {
                    do {
                        if ((read = bis.read()) == -1) {
                            break label74;
                        }

                        ++var6;
                        if (read >= 240 || 128 <= read && read <= 191) {
                            break label74;
                        }

                        if (192 <= read && read <= 223) {
                            read = bis.read();
                            continue label74;
                        }
                    } while(224 > read || read > 239);

                    read = bis.read();
                    if (128 <= read && read <= 191) {
                        read = bis.read();
                        if (128 <= read && read <= 191) {
                            charset = "UTF-8";
                        }
                    }
                    break;
                } while(128 <= read && read <= 191);
            }

            bis.close();
        } catch (Exception var7) {
            var7.printStackTrace();
        }

        return charset;
    }

    public static byte[] readByte(InputStream is) {
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[4096];
            boolean var4 = false;

            int rc;
            while((rc = is.read(buff)) != -1) {
                swapStream.write(buff, 0, rc);
            }

            byte[] in2b = swapStream.toByteArray();
            return in2b;
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    public static byte[] readByte(String fileName) {
        try {
            FileInputStream fis = new FileInputStream(fileName);
            byte[] r = new byte[fis.available()];
            fis.read(r);
            fis.close();
            return r;
        } catch (Exception var3) {
            var3.printStackTrace();
            return null;
        }
    }

    public static boolean writeByte(String fileName, byte[] b) {
        if (b == null) {
            return false;
        } else {
            try {
                BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(fileName));
                fos.write(b);
                fos.close();
                return true;
            } catch (Exception var4) {
                var4.printStackTrace();
                return false;
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();

            for(int i = 0; i < children.length; ++i) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }

    public static void serializeToFile(Object obj, String fileName) {
        try {
            ObjectOutput out = new ObjectOutputStream(new FileOutputStream(fileName));
            out.writeObject(obj);
            out.close();
        } catch (IOException var4) {
            var4.printStackTrace();
        }

    }

    public static void serializeToFile(Object obj, File file) {
        ObjectOutputStream out = null;

        try {
            out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(obj);
        } catch (IOException var12) {
            var12.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException var11) {
                    var11.printStackTrace();
                }
            }

        }

    }

    public static byte[] serializeToByte(Object obj) {
        ObjectOutput out = null;
        ByteArrayOutputStream ot = null;
        byte[] byteArray = null;

        try {
            ot = new ByteArrayOutputStream();
            out = new ObjectOutputStream(ot);
            out.writeObject(obj);
        } catch (IOException var13) {
            var13.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException var12) {
                    var12.printStackTrace();
                }
            }

        }

        if (ot != null) {
            byteArray = ot.toByteArray();
        }

        return byteArray;
    }

    public static Object deserializeFromFile(String fileName) {
        try {
            File file = new File(fileName);
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            Object obj = in.readObject();
            in.close();
            return obj;
        } catch (Exception var4) {
            var4.printStackTrace();
            return null;
        }
    }

    public static Object deserializeFromStream(InputStream ins) {
        try {
            ObjectInputStream in = new ObjectInputStream(ins);
            Object obj = in.readObject();
            in.close();
            return obj;
        } catch (Exception var3) {
            var3.printStackTrace();
            return null;
        }
    }

    public static String inputStream2String(InputStream input, String charset) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(input, charset));
        StringBuffer buffer = new StringBuffer();
        String line = "";

        while((line = in.readLine()) != null) {
            buffer.append(line + "\n");
        }

        return buffer.toString();
    }

    public static String inputStream2String(InputStream input) throws IOException {
        return inputStream2String(input, "utf-8");
    }

    public static File[] getFiles(String path) {
        File file = new File(path);
        return file.listFiles();
    }

    public static void createFolderFile(String path) {
        createFolder(path, true);
    }

    public static void createFolder(String path, boolean isFile) {
        if (isFile) {
            path = path.substring(0, path.lastIndexOf(File.separator));
        }

        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

    }

    public void createFolder(String dirstr, String name) {
        dirstr = stringTrimSufffix(dirstr, File.separator) + File.separator + name;
        File dir = new File(dirstr + name);
        dir.mkdir();
    }

    public static void renameFolder(String path, String newName) {
        File file = new File(path);
        if (file.exists()) {
            file.renameTo(new File(newName));
        }

    }

    public static ArrayList<File> getDiretoryOnly(File dir) {
        ArrayList dirs = new ArrayList();
        if (dir != null && dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles(new FileFilter() {
                public boolean accept(File file) {
                    return file.isDirectory();
                }
            });

            for(int i = 0; i < files.length; ++i) {
                dirs.add(files[i]);
            }
        }

        return dirs;
    }

    public ArrayList<File> getFileOnly(File dir) {
        ArrayList dirs = new ArrayList();
        File[] files = dir.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return file.isFile();
            }
        });

        for(int i = 0; i < files.length; ++i) {
            dirs.add(files[i]);
        }

        return dirs;
    }

    public static boolean deleteFile(String path) {
        File file = new File(path);
        return file.delete();
    }

    public static boolean copyFile(String from, String to) {
        File fromFile = new File(from);
        File toFile = new File(to);
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(fromFile);
            fos = new FileOutputStream(toFile);
            byte[] buf = new byte[4096];

            int bytesRead;
            while((bytesRead = fis.read(buf)) != -1) {
                fos.write(buf, 0, bytesRead);
            }

            fos.flush();
            fos.close();
            fis.close();
            return true;
        } catch (IOException var8) {
            var8.printStackTrace();
            return false;
        }
    }

    public static void backupFile(String filePath) {
        String backupName = filePath + ".bak";
        File file = new File(backupName);
        if (file.exists()) {
            file.delete();
        }

        copyFile(filePath, backupName);
    }

    public static String getFileExt(File file) {
        return file.isFile() ? getFileExt(file.getName()) : "";
    }

    public static String getFileExt(String fileName) {
        int pos = fileName.lastIndexOf(".");
        return pos > -1 ? fileName.substring(pos + 1).toLowerCase() : "";
    }

    public static void copyDir(String fromDir, String toDir) throws IOException {
        (new File(toDir)).mkdirs();
        File[] file = (new File(fromDir)).listFiles();

        for(int i = 0; i < file.length; ++i) {
            if (file[i].isFile()) {
                String fromFile = file[i].getAbsolutePath();
                String toFile = toDir + "/" + file[i].getName();
                copyFile(fromFile, toFile);
            }

            if (file[i].isDirectory()) {
                copyDirectiory(fromDir + "/" + file[i].getName(), toDir + "/" + file[i].getName());
            }
        }

    }

    private static void copyDirectiory(String fromDir, String toDir) throws IOException {
        (new File(toDir)).mkdirs();
        File[] file = (new File(fromDir)).listFiles();

        for(int i = 0; i < file.length; ++i) {
            if (file[i].isFile()) {
                String fromName = file[i].getAbsolutePath();
                String toFile = toDir + "/" + file[i].getName();
                copyFile(fromName, toFile);
            }

            if (file[i].isDirectory()) {
                copyDirectiory(fromDir + "/" + file[i].getName(), toDir + "/" + file[i].getName());
            }
        }

    }

    public static String getFileSize(File file) throws IOException {
        if (file.isFile()) {
            FileInputStream fis = new FileInputStream(file);
            int size = fis.available();
            fis.close();
            return getSize((double)size);
        } else {
            return "";
        }
    }

    public static String getSize(double size) {
        DecimalFormat df = new DecimalFormat("0.00");
        double ss;
        if (size >= 1.073741824E9D) {
            ss = size / 1.073741824E9D;
            return df.format(ss) + " GB";
        } else if (size >= 1048576.0D) {
            ss = size / 1048576.0D;
            return df.format(ss) + " MB";
        } else if (size >= 1024.0D) {
            ss = size / 1024.0D;
            return df.format(ss) + " KB";
        } else {
            return size + " bytes";
        }
    }

    public static String getParentDir(String baseDir, String currentFile) {
        File f = new File(currentFile);
        String parentPath = f.getParent();
        String path = parentPath.replace(baseDir, "");
        return path.replace(File.separator, "/");
    }

    public static String getClassesPath() {
        URL resource = Thread.currentThread().getContextClassLoader().getResource("/");
        if (resource == null) {
            resource = Thread.currentThread().getContextClassLoader().getResource("");
        }

        String templatePath = resource.toString();
        if (templatePath.startsWith("file:/")) {
            templatePath = templatePath.replaceFirst("file:", "");
        }

        templatePath = templatePath.replace("/", File.separator);
        return templatePath;
    }

    public static String getRootPath() {
        String rootPath = getClassesPath();
        String toReplace = "WEB-INF" + File.separator + "classes" + File.separator;
        rootPath = rootPath.replace(toReplace, "");
        return rootPath;
    }

    public static String formatSize(long size, boolean isShowKbOnly) {
        DecimalFormat formatter = new DecimalFormat();
        formatter.setGroupingSize(3);
        formatter.setGroupingUsed(true);
        String resultStr = "";
        if (size < 1024L) {
            formatter.applyPattern("#");
            resultStr = formatter.format(size) + " 字节";
        } else {
            formatter.applyPattern("#.00");
            double dValue;
            if (isShowKbOnly) {
                dValue = (new Long(size)).doubleValue() / 1024.0D;
                resultStr = formatter.format(dValue) + " KB";
            } else if (size < 1048576L) {
                dValue = (new Long(size)).doubleValue() / 1024.0D;
                resultStr = formatter.format(dValue) + " KB";
            } else {
                dValue = (new Long(size)).doubleValue() / 1048576.0D;
                resultStr = formatter.format(dValue) + " MB";
            }
        }

        return resultStr;
    }

    public static String formatPath(String path) {
        if (stringIsNotNull(path)) {
            path = path.replace("\\", File.separator).replace("/", File.separator);
            if (!path.endsWith(File.separator)) {
                path = path + File.separator;
            }

            return path;
        } else {
            return null;
        }
    }

    public static String formatFileName(String fileName) {
        fileName = fileName.replace("\\", "/");
        if (fileName.indexOf("/") != -1) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }

        return fileName;
    }

    public static String formatFileNameInTime(String fileName) {
        StringBuffer buffer = new StringBuffer();
        Calendar c = Calendar.getInstance();
        if (fileName.indexOf(".") != -1) {
            String[] fileNames = fileName.split("\\.");
            buffer.append(fileNames[0]);
            buffer.append("_");
            buffer.append(c.get(1));
            buffer.append(c.get(3));
            buffer.append(c.get(5));
            buffer.append(c.get(10));
            buffer.append(c.get(12));
            buffer.append(c.get(13));
            buffer.append(".");
            buffer.append(fileNames[1]);
        } else {
            buffer.append(fileName);
            buffer.append("_");
            buffer.append(c.get(1));
            buffer.append(c.get(3));
            buffer.append(c.get(5));
            buffer.append(c.get(10));
            buffer.append(c.get(12));
            buffer.append(c.get(13));
        }

        return buffer.toString();
    }




    public static boolean stringIsNull(String str) {
        str = null2Str(str);
        return str.length() == 0;
    }
    public static String null2Str(String str) {
        return str == null ? "" : str.trim();
    }

    public static boolean stringIsNotNull(String s) {
        return !stringIsNull(s);
    }


    public static String stringTrimSufffix(String toTrim, String trimStr) {
        while(toTrim.endsWith(trimStr)) {
            toTrim = toTrim.substring(0, toTrim.length() - trimStr.length());
        }

        return toTrim;
    }



}
